/* eslint-disable */
import axios, { AxiosRequestConfig } from 'axios';
import { ElNotification } from "element-plus";
import router from '../router/index';
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
function request(config: AxiosRequestConfig) {
  const instance = axios.create({
    timeout: 60000,
    baseURL: 'http://127.0.0.1:3007/'
  });
  instance.interceptors.request.use(config => {
    //在发送请求之前做些什么
    //为所有请求头添加token
    NProgress.start()
    if (localStorage.token) { //判断token是否存在
      config.headers.Authorization = localStorage.token; //将token设置成请求头  
      // console.log(localStorage.token);
    }
    return config;
  },
    //对请求错误做些什么
    error => {
      return Promise.reject(error);
    });

  // 添加响应拦截器
  instance.interceptors.response.use(
    //对响应数据做点什么
    response => {
      NProgress.done()
      let res = response.data;
      if (res.code === 200) {
        return response;
      } else if (res.code === 401) {
        ElNotification({
          title: 'Error',
          message: response.data.msg,
          type: 'error',
        })
        router.push("/login");
        // 阻止返回
        return Promise.reject(response.data.msg);
      } else {
        console.log(res);
        ElNotification({
          title: 'Error',
          message: response.data.msg,
          type: 'error',
        })
        // 阻止返回
        return Promise.reject(response.data.msg);
        // return response;
      }
    },
    //对响应错误做点什么
    error => {
      console.log(error);
      if (error.response.data) {
        error.message = error.response.data.msg;
      }
      if (error.response.status === 401) {
        router.push("/login");
      }
      ElNotification({
        title: 'Error',
        message: error.message,
        type: 'error',
      })

      // 阻止返回
      return Promise.reject(error);
    }
  )
  return instance(config);
}

const http = {
  get(url: string, params: any) {
    const config = {
      method: 'get',
      url,
    } as AxiosRequestConfig;
    if (params) config.params = params;
    return request(config);
  },
  post(url: string, params: any) {
    const config = {
      method: 'post',
      url,
    } as AxiosRequestConfig;
    if (params) config.data = params;
    return request(config);
  },
  put(url: string, params: any) {
    const config = {
      method: 'put',
      url,
    } as AxiosRequestConfig;
    if (params) config.params = params;
    return request(config);
  },
  delete(url: string, params: any) {
    const config = {
      method: 'delete',
      url,
    } as AxiosRequestConfig;
    if (params) config.params = params;
    return request(config);
  },
};

export default http;